<script setup lang="ts" name="EaArea">
import { Plus, Search, ArrowDown } from '@element-plus/icons-vue'
import type { EaArea } from './type'
import Form from '@/views/ea/ea-area/Form.vue'

import { checkPermission } from '@/utils/permission'

const baseApi = '/ea/ea-area'
import AreaTree from '@/views/ea/ea-area/Tree.vue'

const changeCurrentNode = (currentNodeKey?: string) => {
  queryParam.parentId = currentNodeKey ?? ''
  onSearch()
}
const { queryParam, loading, dataList, pagination, getList, onSearch, resetFilter, remove, batchRemove } =
  useList<EaArea>({ baseApi, initQueryParam: {} })

defineExpose({
  refresh: onSearch,
  addCondition: (key: keyof EaArea, value: any, refresh = false) => {
    queryParam[key] = value
    if (refresh) onSearch()
  }
})

// const { initRelatedData, relatedData } = useOption({
//   load: {
//     parentIdOptions: {
//       type: 'EaArea',
//       label: 'name',
//       parent: 'parentId',
//       parentPath: 'parentIdsPath',
//       lazyChild: false
//     }
//   }
// })
// initRelatedData()

const sortChange = ({ column, prop, order }: { column: { sortBy?: string }; prop: string; order: string }) => {
  let orderBy: 'ASC' | 'DESC' | undefined
  switch (order) {
    case 'ascending':
      orderBy = 'ASC'
      break
    case 'descending':
      orderBy = 'DESC'
      break
    default:
      orderBy = undefined
  }
  pagination.orderBy = orderBy ? `${column.sortBy ?? prop}:${orderBy}` : undefined
  onSearch()
}

const formRef = ref()
const formTitle = ref('')
const submitting = ref(false)
const formVisible = ref(false)
const addSustainably = ref<boolean>(false)

const openForm = (id?: string) => {
  if (id) {
    addSustainably.value = false
    formTitle.value = '编辑'
  } else {
    addSustainably.value = true
    formTitle.value = '新建'
  }
  formVisible.value = true

  nextTick(() => formRef.value?.init(id))
}

const closeForm = () => {
  formVisible.value = false
}

const submit = (goOn = false) => {
  formRef.value?.submit().then((result: boolean) => {
    if (result) {
      if (!goOn) {
        formVisible.value = false
      }
      formRef.value?.reset()
    }
  })
}

const handleOperation = (code: string, value?: string | string[]) => {
  switch (code) {
    case 'create':
    case 'update':
      openForm(value as string)
      break
    case 'remove':
      remove(value as string)
      break
    case 'batchRemove':
      batchRemove(value as string[])
      break
    default:
      throw new Error(`不存在的操作编码${code}!`)
  }
}

const refreshData = (haveNewData?: boolean) => {
  haveNewData ? onSearch() : getList()
}

const router = useRouter()

const activated = () => {
  nextTick(() => {
    const query = router.currentRoute.value.query
    for (const queryKey in query) {
      queryParam[queryKey as keyof EaArea] = query[queryKey] as any
    }

    onSearch()
  })
}

router.currentRoute.value.meta.keepAlive ? onActivated(activated) : activated()
</script>

<template>
  <el-container class="el-container">
    <el-aside class="el-aside" width="240px">
      <area-tree @click-node="changeCurrentNode" />
    </el-aside>
    <el-container>
      <div class="list-container">
        <div class="list-page">
          <el-space wrap class="list-operation">
            <el-button v-has-permission="'create'" type="primary" :icon="Plus" @click="handleOperation('create')">
              新建
            </el-button>

            <el-space>
              <!-- <span class="search">
                <el-tree-select
                  v-model="queryParam.parentId"
                  placeholder="上级"
                  :data="relatedData.parentIdOptions"
                  filterable
                  default-expand-all
                  check-strictly
                  clearable
                  @change="onSearch"
                />
              </span> -->
              <el-button :icon="Search" type="primary" @click="onSearch">查询</el-button>
              <el-button title="重置查询条件" @click="resetFilter">重置</el-button>
            </el-space>
          </el-space>

          <el-table
            ref="tableRef"
            v-loading="loading"
            class="list-body"
            :data="dataList"
            height="100%"
            stripe
            row-key="id"
            style="border-top: 1px solid var(--el-border-color-lighter)"
            @sort-change="sortChange"
          >
            <el-table-column label="上级" prop="parentIdLabel" show-overflow-tooltip align="center" />
            <el-table-column label="城市名称" prop="name" show-overflow-tooltip align="center" />
            <el-table-column label="城市级别" prop="levelLabel" show-overflow-tooltip align="center">
              <template #default="{ row }: { row: EaArea }">
                <el-tag
                  v-if="row.levelLabel"
                  type="info"
                  :color="(row.levelLabel as LabelValue<{ color?: string }>).ext?.color"
                >
                  {{ (row.levelLabel as LabelValue).label }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="城市编号" prop="cityCode" show-overflow-tooltip align="center" />
            <el-table-column label="操作" fixed="right" :width="120" align="center">
              <template #default="{ row }: { row: EaArea }">
                <el-space>
                  <el-dropdown
                    v-has-permission="['update', 'delete']"
                    @command="(code: string) => handleOperation(code, row.id)"
                  >
                    <el-button text bg type="primary" size="small">
                      {{ $t('operation.more') }}
                      <el-icon :size="16" style="margin-left: 5px">
                        <ArrowDown />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-if="checkPermission('update')" command="update">
                          <el-button link>编辑</el-button>
                        </el-dropdown-item>
                        <el-dropdown-item v-if="checkPermission('delete')" command="remove">
                          <el-button link type="danger">删除</el-button>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-space>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-if="pagination.total"
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 15, 20, 30, 50, 100]"
            small
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="getList()"
            @current-change="getList()"
          />

          <el-dialog v-model="formVisible" width="60%" :title="formTitle" draggable @close="closeForm">
            <Form
              ref="formRef"
              @submitting="(val: boolean) => (submitting = val)"
              @complete="(id?: string, isNew?: boolean) => refreshData(isNew)"
            />

            <template #footer>
              <el-button @click="closeForm">取消</el-button>
              <el-button v-show="addSustainably" type="primary" :loading="submitting" @click="submit(true)">
                保存并继续
              </el-button>
              <el-button type="primary" :loading="submitting" @click="submit()">保存</el-button>
            </template>
          </el-dialog>
        </div>
      </div>
    </el-container>
  </el-container>
</template>

<style scoped lang="scss">
.el-container {
  height: 100%;
}
.el-aside {
  box-sizing: border-box;
  border-right: solid 1px var(--el-menu-border-color);
}
.list-container {
  width: 100%;
  height: 100%;
}
.option {
  display: flex;
  justify-content: space-between;

  .ext {
    font-size: var(--el-font-size-extra-small);
    color: var(--el-text-color-secondary);
  }
}
</style>
